// 递归组装参数
function packParams(param, filter, i = '') {
  console.log(filter)
  const keys = Object.keys(filter)
  const rangeKey = param.filterName + '_' + i
  if (param.childFilters) {
    param.childFilters.forEach((item, i) => {
      packParams(item, filter, i)
    })
  } else if (keys.includes(param.filterName)) {
    param['filterValue'] = filter[param.filterName]
  } else if (keys.includes(rangeKey)) {
    // 范围搜索
    param['filterValue'] = filter[rangeKey]
  }
}

// 获取查询参数
function getQueryParams(param, filter) {
  param = param || {}
  filter = filter || {}
  param = JSON.parse(JSON.stringify(param))
  packParams(param, filter)
  return param
}

// 获取排序参数
function getSortParams(currentSortColumns = []) {
  const sortFields = currentSortColumns.filter((item) => {
    return item.prop && item.order
  }).map(item => {
    const order = item.order === 'descending' ? 'desc' : 'asc'
    return item.prop + ' ' + order
  }).join(',')
  return sortFields
}
import {
  flatTableData,
  isFunction
} from '@admin/utils/index'
import {
  getUserInfo
} from '@admin/utils/auth'
import {
  getMainData,
  commonInvoke,
  multiCommonInvoke
} from '@admin/api/common.js'
import {
  createTableColumn
} from '../utils/table'
import {
  macroVars
} from '../utils/const'
import {
  runFnInVm
} from '@admin/packages/async-component/src/utils.js'

export default {
  data() {
    return {
      tableColumn: [], // 表格列
      tableInfo: {}, // 后台返回的表信息
      tableData: [], // 表数据
      listLoading: false,
      currentPage: 1,
      pageSize: 20,
      total: 0,
      personalization: '',
      tabTotal: '', // tab数量，与total一致，如果值===''则不显示数量
      tabTotals: {}, // 多个tab页数量
      currentSortColumns: [], // 只支持一个排序
      pageSizes: [10, 20, 50, 100, 200]
    }
  },
  computed: {
    callback: function() {
      return this.gridInfo.callback || {}
    },
    extendQuery: function() {
      return this.callback?.extendQuery || ''
    },
    completeRequest: function() {
      return this.callback?.completeRequest || ''
    },
    beforeBinded: function () {
      return this.callback?.beforeBinded || ''
    },
    onBinded: function () {
      return this.callback?.onBinded || ''
    },
    lockColumnCount: function () {
      if (this.gridInfo?.enableCustomColumn && this.personalization) {
        try {
          return JSON.parse(this.personalization)?.lockColumnCount || 0
        } catch (e) {
          console.error(e)
          return 0
        }
      } else if (this.gridInfo?.lockColumnCount) {
        return Number(this.gridInfo.lockColumnCount)
      } else {
        return 0
      }
    },
    sortColumns: function() {
      if (this.gridInfo?.sortColumns) {
        return (this.gridInfo.sortColumns || '').split(',')
      } else {
        return []
      }
    },
    tableAttr: function() {
      const attrConfig = this.gridInfo?.tableAttr
      const maxHeight = this.gridInfo?.maxHeight
      let configAttr = {}
      if (maxHeight) {
        configAttr['max-height'] = maxHeight
      }
      if (attrConfig) {
        configAttr = Object.assign({}, configAttr, window.$CD[attrConfig])
      }
      return configAttr
    },
    defaultSort: function() {
      const firstSort = this.currentSortColumns[0] || null
      if (firstSort && firstSort.order) {
        return {
          prop: firstSort.prop,
          order: firstSort.order
        }
      }
      return {}
    },
    enablePaging: function() {
      if (Object.keys(this.gridInfo).includes('enablePaging')) {
        return this.gridInfo.enablePaging == 1
      } else {
        return true
      }
    },
    // 默认隐藏操作按钮
    defaultHideButton: function() {
      if (Object.keys(this.gridInfo).includes('defaultHideButton')) {
        return !!this.gridInfo.defaultHideButton
      } else {
        return false
      }
    },
    hideColumns: function() {
      if (this.gridInfo?.hideColumns) {
        return (this.gridInfo.hideColumns || '').split(',')
      } else {
        return []
      }
    },
    fullTextSearch: function() {
      if (Object.keys(this.gridInfo).includes('fullTextSearch')) {
        return !!this.gridInfo.fullTextSearch
      } else {
        return false
      }
    },
    // 富列表
    humanDisplay: function() {
      if (this.gridInfo?.humanDisplay) {
        return (this.gridInfo.humanDisplay || '').split(',')
      } else {
        return []
      }
    },
    // 主表可行内编辑列
    enableEditCols: function () {
      return this.gridInfo?.editColumns
    },
    // 允许主表行内编辑
    enableTableEdit: function () {
      return this.enableEditCols && !!this.enableEditCols.length && (this.btns || []).some(i => i.btnType == 31)
    },
  },
  beforeMount: function() {
    this.setTableSize()
  },
  mounted: function() {

  },
  methods: {
    setTableSize() {
      if (this.gridInfo.pageCountList) {
        this.pageSizes = Array.from(this.gridInfo.pageCountList.split(',')).map(i => Number(i)).sort((pre, next) => pre > next ? 1 : -1)
      }
      if (this.gridInfo.defaultPageSize) {
        this.pageSize = Number(this.gridInfo.defaultPageSize)
      }
    },
    btnClick(e, scope) {
      this.getTableInstance().setCurrentRow(scope.row)
      e.stopPropagation()
    },
    // 表格行内编辑
    tableEdit(e, scope) {
      scope.row._edit = true
    },
    // 表格行内编辑
    tableSave(e, scope) {
      scope.row._edit = false
    },
    // 加载表格配置
    loadConfig(force = false, lockColumnCount = 0, useLocalFixedColumns = false) {
      // 防止重复加载
      if (this.tableColumn.length && !force) {
        return
      }
      let tmpTableColumn = []
      tmpTableColumn = createTableColumn(this.tableInfo, (force && !useLocalFixedColumns) ? lockColumnCount : this.lockColumnCount, this.callback, this.sortColumns, this.gridInfo, this.tableLinkBtns, this)
      // 新增索引号
      const indexName = this.$tra('table.index', '序号')
      if (this.gridInfo.enableIndexRow) {
        tmpTableColumn.unshift({
          type: 'index',
          fixed: 'left',
          width: '70',
          label: indexName
        })
      }
      // 新增列表选择
      if (this.gridInfo.enableCheckBox) {
        tmpTableColumn.unshift({
          type: 'selection',
          fixed: 'left',
          label: '多选'
        })
      }
      // 扩展列
      if (window.$CD && isFunction(window.$CD[this.callback.setTableColumn])) {
        window.$CD[this.callback.setTableColumn](tmpTableColumn, this.gridInfo, this)
      }
      // 新增列表选择
      if (this.tableBtns.length) {
        const actionName = this.$tra('table.action', '操作')
        tmpTableColumn.push({
          label: actionName,
          prop: 'oper',
          fixed: 'right',
          className: 'cell-operate',
          render: (h, scope) => {
            // 按钮显示规则
            // 显隐方法实现的按钮
            const displayFunctionBtns = []
            const btns = this.tableBtns.filter(btn => {
              const {
                renderSetting
              } = btn
              if (renderSetting && renderSetting.displayScript) {
                displayFunctionBtns.push(btn.code)
                const {
                  value,
                  error
                } = runFnInVm(renderSetting.displayScript, {
                  tableData: scope.row,
                  btn: btn,
                  instance: this
                })
                if (error) {
                  console.error('脚本执行错误:' + error)
                }
                return value
              }
              return true
            }).filter(btn => {
              if (displayFunctionBtns.includes(btn.code)) {
                return true
              }
              let showBtn = true
              if (this.defaultHideButton) {
                showBtn = false
              }
              // 默认状态
              const defaultBtn = showBtn
              if (this.gridInfo.tableButtonRule && this.gridInfo.tableButtonRule.length) {
                this.gridInfo.tableButtonRule.forEach(rule => {
                  const {
                    field,
                    hideButtons,
                    showButtons,
                    oprator,
                    value,
                    type = 1
                  } = rule
                  // type:1从列表获取数据 type:2从表单获取数据
                  const diffBtns = this.defaultHideButton ? showButtons : hideButtons
                  if ((diffBtns || '').split(',').includes(btn.code)) {
                    let diffData = scope.row
                    // 表单页面数据对比
                    if (type == 2) {
                      diffData = this.tempInstance.getFormData()
                    } else if (type == 3) {
                      // 弹框表单对比
                      diffData = this.complexForm.getFullFormData()
                    }
                    if (oprator == 3) {
                      if (macroVars.includes(value)) {
                        const { code, id, name } = getUserInfo()
                        if (value === '@@S.userId') {
                          if (diffData[field] == id) {
                            showBtn = !defaultBtn
                          }
                        }
                      } else if (diffData[field] == value) {
                        showBtn = !defaultBtn
                      }
                    } else if (oprator == 4) {
                      if (macroVars.includes(value)) {
                        const { code, id, name } = getUserInfo()
                        if (value === '@@S.userId') {
                          if (diffData[field] != id) {
                            showBtn = !defaultBtn
                          }
                        }
                      } else if (diffData[field] != value) {
                        showBtn = !defaultBtn
                      }
                    }
                  }
                })
              }
              return showBtn
            })
            return (
              <table-operate is-flow={this.isFlow || false} btns={btns} pBtn={this.btn || {}} type='text' nativeOnClick={(e) => { this.btnClick(e, scope) }} tableRow={scope.row} gridInfo={this.gridInfo} attachData={this.attachData || {}} />
            )
          }
        })
      }
      console.log(tmpTableColumn)
      this.tableColumn = tmpTableColumn
    },

    // 拼接列表查询和导出公共参数
    getRequestParams() {
      // 新版查询条件
      const sortParam = getSortParams(this.currentSortColumns)
      const query = {
        SortField: sortParam
      }
      const searchParam = JSON.parse(JSON.stringify((this.search.filter || []))).map(item => {
        let value = typeof (this.filter[item.columnCode]) === 'undefined' ? '' : this.filter[item.columnCode]
        // 范围
        if(item.filterType == '5'){
          if(this.filter[item.columnCode+'_0']){
            value = [this.filter[item.columnCode+'_0'],this.filter[item.columnCode+'_1']].join(',')
          }
        }
        return {
          columnCode: item.columnCode,
          filterType: item.filterType,
          value: value
        }
      })
      query['PageIndex'] = this.currentPage
      query['PageSize'] = this.pageSize
      const param = {
        pageId: window.$CD.pageId,
        queryParam: JSON.stringify(query),
        searchParam: searchParam ? JSON.stringify(searchParam) : undefined
      }
      if (this.searchType === 'fullsearch') {
        param['fullTextSearch'] = this.searchText
      }
      return param
    },
    // 校验查询条件表单是否必填
    tableFilterValidate() {
      return new Promise((resolve, reject) => {
        if (this.$refs.tableFilter){
          this.$refs.tableFilter.validate().then(valid=>{
            if(valid){
              resolve()
            }else{
              reject()
            }
          })
        }else{
          resolve()
        }
      })
    },
    /**
     * 获取列表数据
     * @param {*} loadConfig 是否重新加载配置
     */
    getList(loadConfig = false) {
      this.tableFilterValidate().then(() => {
        const param = this.getRequestParams()
        this.listLoading = true
        this.tabTotal = ''
        if (window.$CD[this.extendQuery]) {
          window.$CD[this.extendQuery](param)
        }
        getMainData(param).then((res) => {
          const {
            tableInfo,
            data,
            totalCount,
            personalization
          } = res.data
          this.tableInfo = tableInfo
          this.personalization = personalization
          if (loadConfig) {
            this.loadConfig(true, 0, true)
          }
          this.tableData = flatTableData(data)
          if (window.$CD[this.beforeBinded]) {
            window.$CD[this.beforeBinded](this.tableData, this)
          }
          this.total = totalCount
          this.tabTotal = totalCount
          if (this.currentTab) {
            this.$set(this.tabTotals, this.currentTab.title_code, totalCount)
          }
        }).finally(() => {
          if (window.$CD[this.completeRequest]) {
            window.$CD[this.completeRequest](this)
          }
          if (window.$CD[this.onBinded]) {
            window.$CD[this.onBinded](this.tableData, this)
          }
          setTimeout(() => {
            this.commonInstance && this.commonInstance.setTableMaxHeight()
            this.listLoading = false
          }, 100)
        })
      }).catch(()=>{
        this.tableData = []
      })
    },
    handleSearch() {
      // 清空tab页数统计
      this.tabTotals = {}
      this.currentPage = 1
      this.getList()
      console.log(this.filter)
    },
    handleSizeChange(val) {
      this.currentPage = 1
      this.pageSize = val
      this.getList()
    },
    handleCurrentChange() {
      this.getList()
    },
    handleSortChange(column) {
      this.currentSortColumns = [column]
      this.getList()
    },
    // 兼容方案获取行数据，行获取不到会获取复选框
    getComCurrentRow() {
      this.getTableInstance()
      return new Promise((resolve, reject) => {
        const currentRow = this.tableInstance.currentRow
        if (currentRow) {
          resolve(currentRow)
        }
        const selectedRows = this.tableInstance.multipleSelection
        if (selectedRows && selectedRows.length === 1) {
          resolve(selectedRows[0])
        }
        reject(this.$tra('form.selectPlaceholder', '请选择'))
      })
    },
    // 获取表数据
    getTableData() {
      return this.tableData
    },
    // 主表保存
    saveMainTable() {
      const tableData = this.getTableData()
      if (tableData.length === 0) {
        return Promise.resolve()
      }
      // 获取子表保存按钮
      const saveBtn = this.btns.find(i => i.btnType == 31)
      const param = {
        funcCode: saveBtn.code,
        dataset: [{
          ...this.attachData,
          jsonStr: JSON.stringify(tableData)
        }],
        pageId: window.$CD.pageId
      }
      return multiCommonInvoke(param)
    },
    // 子表保存
    saveSubTable() {
      const tableData = this.getTableData()
      if (tableData.length === 0) {
        return Promise.resolve()
      }
      // 获取子表保存按钮
      const saveBtn = this.btns.find(i => i.btnType == 32)
      const param = {
        funcCode: saveBtn.code,
        data: {
          ...this.attachData,
          jsonStr: JSON.stringify(tableData)
        },
        pageId: window.$CD.pageId
      }
      return commonInvoke(param)
    }
  }
}
